import { useEffect, useState } from "react";

interface IUrl{
  pathname: string,
  qs: {[key:string]:string},
  hash: string,
}
function useUrl(){
  const [info, setInfo] = useState<IUrl>({} as IUrl);
  function parseUrl(){
    let { pathname, hash, search } = window.location;
    hash = hash.slice(1);
    const qs:{[key:string]:string} = {};
    if (search){
      let temps = search.slice(1).split('&');
      temps.forEach(item=>{
        let [key, value] = item.split('=');
        qs[key] = decodeURIComponent(value);
      })
    }
    setInfo({
      pathname,
      qs,
      hash
    })
  }
  useEffect(() => {
    parseUrl();
  }, []);
  window.addEventListener('hashchange', parseUrl);
  window.addEventListener('popstate', parseUrl);
  return info;
}

export default useUrl;
